<template>
  <div>
    <div style="display: none;">
      <a-button type="primary" @click="addBtnClkFn">添加</a-button>
    </div>

    <div class="table">
      <a-table rowKey="id" :columns="eduExperienceColumns" :data-source="eduExperienceData" :pagination="false">
        <template v-for="col in eduExperienceColumns" :slot="col.dataIndex" slot-scope="text, record">
          <div :key="col.dataIndex">
            <a-input v-if="
                record.editable &&
                (col.dataIndex == 'schoolName' || col.dataIndex == 'majorName')
              " style="margin: -5px 0" :value="text" @change="
                (e) => handleChange(e.target.value, record.key, col.dataIndex)
              "></a-input>
            <a-date-picker style="width: 200px" @change="
                (date, dateString) =>
                  dateOnChange(dateString, record.key, col.dataIndex)
              " v-else-if="
                record.editable &&
                (col.dataIndex == 'beginDate' || col.dataIndex == 'endDate')
              " :default-value="moment(moment(text), dateFormat)" />
            <template v-else>{{ text | dateFormatFilter }}</template>
          </div>
        </template>
        <span slot="opera" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a @click="() => save(record.key)">保存</a>
              <a-popconfirm title="确定取消?" @confirm="() => cancel(record.key)">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
              <a-divider type="vertical" />
              <a @click="() => delectClkFn(record.id)">删除</a>
            </span>
          </div>
        </span>
      </a-table>
    </div>

    <!-- modal -->
    <a-modal title="新增教育经历" centered :visible="modalShow" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
      <a-form-model :model="modalForm" :label-col="labelCol" :wrapper-col="wrapperCol" ref="modalFormDom">
        <a-form-model-item label="学校名称" prop="school">
          <a-input v-model="modalForm.school" placeholder="请输入学校名称" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="所学专业" prop="major">
          <a-input v-model="modalForm.major" placeholder="请输入所学专业" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="入学时间" prop="entryDate">
          <a-date-picker v-model="modalForm.entryDate" :style="setWidth" @change="goSchoolDateOnChange" placeholder="请选择入学时间" />
        </a-form-model-item>
        <a-form-model-item label="毕业时间" prop="graduateDate">
          <a-date-picker v-model="modalForm.graduateDate" :style="setWidth" @change="graduateDateOnChange" placeholder="请选择毕业时间" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { transferDate } from '@/utils/util'
import datas from "@/utils/data";
import moment from "moment";
import { eduHistoryAddOrUpdateApi, eduHistory, eduHistoryDelByIdApi } from "@/services/employeeDetail";

export default {
  name: "tabs4",
  props: {
    eduHistoryList: Array,
  },
  filters: {
    dateFormatFilter (val) {
      if (typeof val == "number") {
        return transferDate(val, 0);
      } else {
        return val;
      }
    },
  },
  watch: {
    eduHistoryList (n) {
      this.eduExperienceData = n
    }
  },
  data () {
    this.cacheData = this.eduHistoryList.map((item) => ({ ...item }));
    return {
      eduExperienceColumns: datas.eduExperienceColumns,
      eduExperienceData: this.eduHistoryList,
      editingKey: "",
      dateFormat: "YYYY/MM/DD",
      modalShow: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      modalForm: {
        school: "",
        major: "",
        entryDate: "",
        graduateDate: "",
      },
      setWidth: "width: 276px",
      confirmLoading: false,
    };
  },
  methods: {
    moment,

    getData () {
      /**
       * @description: 教育经历接口
       * @param {*}
       * @return {*}
       */
      let params = {
        userId: this.$Storage.get('employDetail_userId')
      }

      eduHistory(params).then((res) => {
        let { code } = res.data;
        if (code == 200) {
          this.$emit('updatesEduData')
        }
      });
    },

    handleChange (value, key, column) {
      const newData = [...this.eduExperienceData];
      const target = newData.filter((item) => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.eduExperienceData = newData;
      }
    },
    dateOnChange (dateString, key, column) {
      const newData = [...this.eduExperienceData];
      const target = newData.filter((item) => key === item.key)[0];
      if (target) {
        target[column] = dateString;
        this.eduExperienceData = newData;
      }
    },
    edit (key) {
      const newData = [...this.eduExperienceData];
      const target = newData.filter((item) => key === item.key)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.eduExperienceData = newData;
      }
    },
    save (key) {
      const newData = [...this.eduExperienceData];
      const newCacheData = [...this.cacheData];
      const target = newData.filter((item) => key === item.key)[0];
      const targetCache = newCacheData.filter((item) => key === item.key)[0];
      if (target && targetCache) {
        delete target.editable;
        this.eduExperienceData = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = "";

      // 编辑
      let { id, schoolName, majorName, beginDate, endDate } = target;
      let params = {
        id,
        userId: this.$Storage.get("employDetail_userId"),
        beginDateStr: beginDate,
        endDateStr: endDate,
        schoolName,
        majorName,
        // education: "小学"
      };
      this.addUpdatesEduHistoryPackApi(params);
    },
    cancel (key) {
      const newData = [...this.eduExperienceData];
      const target = newData.filter((item) => key === item.key)[0];
      this.editingKey = "";
      if (target) {
        Object.assign(
          target,
          this.cacheData.filter((item) => key === item.key)[0]
        );
        delete target.editable;
        this.eduExperienceData = newData;
      }
    },
    addBtnClkFn () {
      this.modalShow = true;
      this.$nextTick(() => {
        this.$refs["modalFormDom"].resetFields();
      });
    },
    handleOk () {
      // 新增
      this.confirmLoading = true;

      let { school, major, entryDate, graduateDate } = this.modalForm;
      let params = {
        userId: this.$Storage.get("employDetail_userId"),
        beginDateStr: entryDate,
        endDateStr: graduateDate,
        schoolName: school,
        majorName: major,
        // education: "小学"
      };

      this.addUpdatesEduHistoryPackApi(params);
    },

    addUpdatesEduHistoryPackApi (params) {
      this.modalShow = false;
      this.confirmLoading = false;
      eduHistoryAddOrUpdateApi(params).then((res) => {
        let { code, msg } = res.data;
        if (code === 200) {
          this.$message.success(msg);
          this.getData();
        } else if (code === 400) {
          this.$message.error(msg);
        }
      });
    },

    handleCancel () {
      this.modalShow = false;
    },
    goSchoolDateOnChange (date, dateString) {
      console.log(date, dateString);
      this.modalForm.entryDate = dateString;
    },
    graduateDateOnChange (date, dateString) {
      console.log(date, dateString);
      this.modalForm.graduateDate = dateString;
    },

    delectClkFn (id) {
      let params = {
        id
      };
      eduHistoryDelByIdApi(params).then((res) => {
        let { code, msg } = res.data;
        if (code === 200) {
          this.$message.success(msg);
          this.$emit("updatesEduData");
        } else if (code === 400) {
          this.$message.error(msg);
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
// .table {
//   margin: 20px 0 0;
// }
.editable-row-operations a {
  margin-right: 8px;
}
</style>